<?php
namespace App\Services\Base;

use Illuminate\Support\Facades\DB;
use App\Models\Base\DistrictModel;
use App\Exceptions\Response\Service\ServiceException;
use App\Exceptions\Response\Service\ServiceCode;

class DistrictService
{

    /**
     * 获取城市或省份数据
     *
     * @param $id 地址ID            
     * @throws ServiceException
     * @return array
     */
    public function findSignByCity($id)
    {
        $fields = DB::raw('c.id as city,c.name as city_name,p.id as province,p.name as province_name');
        $collection = DistrictModel::dbTable('c')->select($fields)
            ->leftJoin(DistrictModel::TABLENAME . ' as p', 'p.id', '=', 'c.upid')
            ->where('c.id', $id)
            ->get();
        if (! $collection->count()) {
            throw new ServiceException(ServiceCode::SERVICE_DATA_NOT_EXIST);
        }
        $item = $collection->shift();
        
        if (! $item['province']) {
            $data['province'] = $item['city'];
            $data['province_name'] = $item['city_name'];
        } else {
            $data = $item;
        }
        return $data;
    }
}